import {Component, HostListener, OnDestroy, OnInit} from "@angular/core";
import {LocalStorageService} from "../local-storage-service";
import {CommService} from "../comm-service";
import {MyhttpService} from "../myhttp.service";

declare var AMap: any;
declare var $: any;

@Component({
  template: `
    <div class="n_room">
      <div class="lpanel" [style.height]="pagesize.pageh" [style.width]="pagesize.lpanelwstr">
        <div class="arrBtn" (click)="lpanelCtr('l')">
          <i *ngIf="pagesize.lpanelshow" class="fa fa-chevron-left"></i>
          <i *ngIf="!pagesize.lpanelshow" class="fa fa-chevron-right"></i>
        </div>
        <div class="container-fluid" id="lformRoom">
          <div class="row">
            <form class="form-horizontal" role="form">
              <div class="col-lg-12">
                <div class="form-group">
                  <label class="col-lg-3 control-label">查询范围：</label>
                  <div class="col-lg-8 myinput-room">
                    <div class="form-control" style="cursor: pointer;position: relative" (click)="searchTreectr()">
                      {{s_obj.ksgljgidmc}}
                      <div class="myicon">
                        <i class="fa fa-chevron-down" *ngIf="!treeshow"></i>
                        <i class="fa fa-chevron-left" *ngIf="treeshow"></i>
                      </div>
                    </div>
                    <div class="searchtree" *ngIf="treeshow">
                      <div *ngIf="searchtreeObj">
                        <search-tree [o]="searchtreeObj" (outhander)="searchtreeHander($event)"></search-tree>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-lg-12">
                <div class="form-group">
                  <label class="col-lg-3 control-label">查询内容：</label>
                  <div class="col-lg-8">
                    <select class="form-control" name="cxnr" id="cxlxSelect" [(ngModel)]="s_obj.cxlx"
                            (change)="search_n()"></select>
                  </div>
                </div>
              </div>
            </form>
          </div>
          <div class="row">
            <div class="col-lg-12" id="table_rw">
              <div class="portlet box blue">
                <div class="portlet-title">
                  <div class="caption">
                    运送任务列表
                  </div>
                </div>
                <div class="portlet-body">
                  <div class="row">
                    <div class="col-lg-12">
                      <table></table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-lg-12" id="table_zdsb">
              <div class="portlet box blue">
                <div class="portlet-title">
                  <div class="caption">
                    手持终端列表
                  </div>
                </div>
                <div class="portlet-body">
                  <div class="row">
                    <div class="col-lg-12">
                      <table></table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-lg-12" id="table_dzbqsb">
              <div class="portlet box blue">
                <div class="portlet-title">
                  <div class="caption">
                    电子标签列表
                  </div>
                </div>
                <div class="portlet-body">
                  <div class="row">
                    <div class="col-lg-12">
                      <table></table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="rpanel" [style.height]="pagesize.pageh" [style.width]="pagesize.rpanelwstr">
        <div id="mapdiv"></div>
      </div>
    </div>
    <div class="modal fad" id="mymodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog smmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">选择查询时间段</h4>
          </div>
          <div class="modal-body">
            <div class="row">
              <form class="form-horizontal" role="form">
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="col-lg-3 control-label">时间段：</label>
                    <div class="col-lg-8">
                      <div class="input-group">
                        <span class="input-group-addon"><i class="fa fa-calculator"></i></span>
                        <input type="text" class="form-control datetimepickerB_content" id="s_sbtime"
                               [value]="s_obj_lsgj.kssj" readonly>
                        <span class="input-group-addon">至</span>
                        <input type="text" class="form-control datetimepickerE_content" id="s_edtime"
                               [value]="s_obj_lsgj.jssj" readonly>
                        <span class="input-group-addon"><i class="fa fa-calculator"></i></span>
                      </div>
                      <span class="help-block text-danger" *ngIf="timerangewarnflag">{{timerangewarntext}}</span>
                    </div>
                  </div>
                </div>
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="col-lg-3 control-label">回放速度：</label>
                    <div class="col-lg-8">
                      <div class="mt-radio-list" *ngIf="hfSpeedArr.length">
                        <div class="mt-radio-inline" *ngFor="let item of hfSpeedArr;index as index">
                          <label class="mt-radio" *ngIf="index==0">
                            <input type="radio" checked [value]="item.speed" name="hfspeed"
                                   [attr.mc]="item.name"> {{item.name}}
                            <span></span>
                          </label>
                          <label class="mt-radio" *ngIf="index>0">
                            <input type="radio" [value]="item.speed" name="hfspeed"
                                   [attr.mc]="item.name"> {{item.name}}
                            <span></span>
                          </label>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <!--<div class="col-lg-12">-->
                <!--<div class="form-group">-->
                <!--<label class="control-label col-lg-3">测试：</label>-->
                <!--<div class="col-lg-8">-->
                <!--<input type="text" class="form-control" name="testlx" [(ngModel)]="testlx"/>-->
                <!--</div>-->
                <!--</div>-->
                <!--</div>-->
                <div class="col-lg-12" id="dwlx" style="display:none;">
                  <div class="form-group">
                    <label class="col-lg-3 control-label">定位类型：</label>
                    <div class="col-lg-8">
                      <div>
                        <div *ngFor="let item of dwlxarr" class="col-lg-4">
                          <div class="mt-checkbox-inline">
                            <label class="mt-checkbox">
                              <input type="checkbox" [value]="item.lx"/> {{item.name}}
                              <span></span>
                            </label>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
            <button type="button" class="btn btn-primary" (click)="trailIng()">确定</button>
          </div>
        </div>
      </div>
    </div>


  `,
  styles: [
    ".n_room{overflow-x: auto;overflow-y: hidden;position: relative;margin: 0px auto}",
    ".n_room>.lpanel{position: absolute;left:0px;top: 0px;overflow-y: hidden;background-color: #ffffff;}",
    ".n_room>.rpanel{position: relative;margin-left: 475px}",
    //左侧 z-index =100要大于form的
    ".lpanel>.arrBtn{position: absolute;z-index: 100; top: 5px;right: 0px; width: 20px;height: 50px;line-height: 50px;text-align: center;color: #ffffff;background-color: #3598DC; cursor: pointer}",
    ".lpanel>#lformRoom{padding-top: 20px}",
    ".myinput-room{position: relative;height: 34px}",
    ".myicon{position: absolute;width: 30px;height: 30px;right: 5px;top: 0px;text-align: center;padding-top: 5px;cursor: pointer}",
    ".searchtree{z-index: 400;width: 100%;background-color: #fff; position: absolute;top: 35px;left: 0px;}",
    "#table_rw{display: none}",
    "#table_zdsb{display: none}",
    "#table_dzbqsb{display: none}",
    // 右侧
    "#mapdiv{width: 100%;height: 100%}",
    "#dwlx .col-lg-4{padding-left:0;}"
  ]
})
export class LsgJComponent implements OnInit, OnDestroy {
  userinfo: any;
  sysBase: string;
  pagesize: any = {
    pageh: "0px",  // 整个页面的高度，自适应浏览器的窗口高度
    lpanelwinit: 475, // 左侧宽度
    lpanelwstr: "475px",
    rpanelwinit: 0, // 右侧宽度，自适应浏览器的窗口宽度
    rpanelwstr: "0px",
    lpanelshow: true
  };
  map: any;   // 地图实例
  s_obj: any = {
    ksgljgidmc: "",
    ksgljgid: "",
    cxlx: "sjysrw", // sjysrw--运送任务列表 dzbqsb--电子标签设备列表 sczdsb --手持终端设备列表
    ksjhbh: ""
  };
  treeshow: boolean = false;
  searchtreeObj: any;
  //查询历史轨迹的时间段
  s_obj_lsgj: any = {
    cxlx: "", // sjysrw/dzbqsb/sczdsb
    id: "",  //运送任务编号/标签ID/手持终端ID
    kssj: "",
    jssj: '',
    dwlxList: []
  }
  timerangewarnflag: boolean = false;
  timerangewarntext: string = "";
  hfSpeed: number = 400;  // 回放速度， 默认等级 ---极快的  400 km/h
  hfSpeedArr: any[] = [{
    speed: 10000,
    name: "极快"
  }, {
    speed: 4000,
    name: "快"
  }, {
    speed: 1000,
    name: "中"
  }, {
    speed: 400,
    name: "慢"
  }, {
    speed: 100,
    name: "极慢"
  }];
  hfwcExistSpeed: number = 100000;  // 测试，存在误差的分界线 速度
  carmarker: any; // 车辆marker
  passedPolyline: any; // 路径对象
  graspobj: any; // 轨迹纠偏对象
  cllx: string = 'jp'; // 处理类型 jp-纠偏   ph--平滑
  dwlxarr: any[] = [{
    lx: "gps",
    name: "GPS定位"
  }, {
    lx: "lac",
    name: "基站定位"
  }, {
    lx: "phone",
    name: "终端定位"
  }]

  /**
   * 加载 机构树
   */
  initsearchTree(): void {
    this.searchtreeObj = {
      treetype: "cstree",//树选型
      nodelx: "ksgljg",//树节点类型
      id: this.userinfo.csid,//场所编号
      type: this.userinfo.cslx,//机构类型
      text: this.userinfo.csmc,//场所名称
      treeheight: 400,
      clickroot: false
    };
    this.s_obj.ksgljgidmc = this.userinfo.csmc;
    this.s_obj.ksgljgid = this.userinfo.csid;
    this.search_n();
  }

  /**
   * 点击搜索树
   * @param e
   */
  searchtreeHander(e: any): void {
    const type = e.type;
    if (type === "clicknode") {
      const data = e.data;
      const nodeid = data.nodeid;
      this.s_obj.ksgljgid = nodeid; // 考试管理机构id/ 标准化考点id//场所编号
      this.s_obj.ksgljgidmc = data.nodetext;
      this.treeshow = false;
      this.search_n();
    }
  }

  /**
   * 搜索 任务/手持终端设备/电子标签设备
   */
  search_n(): void {
    const cxlx = this.s_obj.cxlx;
    this.map.clearMap();
    this.carmarker = null;
    this.passedPolyline = null;
    switch (cxlx) {
      case "sjysrw":
        $("#table_rw").show();
        $("#table_zdsb").hide();
        $("#table_dzbqsb").hide();
        this.getall_rw();
        break;
      case "sczdsb":
        $("#table_rw").hide();
        $("#table_zdsb").show();
        $("#table_dzbqsb").hide();
        this.getall_zdsb();
        break;
      case "dzbqsb":
        $("#table_rw").hide();
        $("#table_zdsb").hide();
        $("#table_dzbqsb").show();
        this.get_bqsb();
        break;
    }
  }

  /**
   * 获取所欲的运送任务
   * 1： 表格生成--客户端分页
   * 2： 实时轨迹处理
   */
  getall_rw(): void {
    const url = "sjgz/gjcx/ysrwlb";
    this.itservice.kwPtPost(url, {
      ksgljgid: this.s_obj.ksgljgid,
      ksjhbh: this.s_obj.ksjhbh,
      rwwczt: "",  // 	任务完成状态
      pageNum: 1,
      pageSize: 9999
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const ysrwList = resp.ysrwList;
            if (ysrwList && ysrwList.length) {
              this.inittable_rwClient(ysrwList);
            } else {
              this.inittable_rwClient([]);
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getall_rw();
        }
      });
    });
  }

  /**
   * 获取所欲的手持终端设备
   * 1： 表格生成--客户端分页
   * 2： 实时轨迹处理
   */
  getall_zdsb(): void {
    const url = "sjgz/gjcx/sczdsblb";
    this.itservice.kwPtPost(url, {
      ksgljgid: this.s_obj.ksgljgid,
      sfqy: "", // 是否启用
      pageNum: 1,
      pageSize: 9999
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const sczdList = resp.sczdList;
            if (sczdList && sczdList.length) {
              this.inittable_zdsbClient(sczdList);
            } else {
              this.inittable_zdsbClient([]);
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getall_rw();
        }
      });
    });
  }

  /**
   * 获取所欲的电子标签
   * 1： 表格生成--客户端分页
   * 2： 实时轨迹处理
   */
  get_bqsb(): void {
    const url = "sjgz/gjcx/dzbqsblb";
    this.itservice.kwPtPost(url, {
      ksgljgid: this.s_obj.ksgljgid,
      ksjhbh: this.s_obj.ksjhbh,
      sfqy: "", // 是否启用
      pageNum: 1,
      pageSize: 9999
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const dzbqList = resp.dzbqList;
            if (dzbqList && dzbqList.length) {
              this.inittable_bqsbClient(dzbqList);
            } else {
              this.inittable_bqsbClient([]);
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getall_rw();
        }
      });
    });
  }

  inittable_rwClient(data: any): void {
    const that = this;
    $("#table_rw table").bootstrapTable('destroy');
    const obj = {
      classes: 'table  table-bordered', //没有 border,默认是 table table-hover
      locale: 'zh-CN',
      sidePagination: "client", //分页方式：client 客户端分页，server 服务端分页（*）
      pageSize: 20, //每页的个数
      pageNumber: 1, //默认是1
      pageList: [20, 30],
      pagination: true, //是否显示分页（*）  默认false
      paginationHAlign: 'right', //right, left
      paginationVAlign: 'bottom', //bottom, top, both
      paginationDetailHAlign: 'left', //right, left
      data: data,
      columns: [{
        title: '运送任务名称',
        field: 'ysrwmc',
        cellStyle: function () {
          return {
            classes: 'td1'
          }
        },
      }, {
        title: '操作',
        field: 'caozuo',
        cellStyle: function () {
          return {
            classes: 'td2'
          }
        },
        events: that.myevents,
        formatter: function (v) {
          let str: string = "";
          str += "<button type='button' class='btn btn-xs btn-info info_rw'><i class='fa fa-paper-plane'></i> 查看轨迹</button>";
          return str;
        }
      }],
    };
    const ajustHeight = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 220;
    if (this.sysBase == "61") {
      obj.pageSize = 50;
      obj.pageList = [50];
      obj["hiddenPageinfoLink"] = true;
      obj["paginationLoop"] = true;
      obj["paginationPreText"] = "<i class='fa fa-arrow-left'></i>上一页";
      obj["paginationNextText"] = "下一页<i class='fa fa-arrow-right'></i>";
      obj["height"] = ajustHeight;
    } else {
      // 这个页面用陕西的配置模式
      obj.pageSize = 50;
      obj.pageList = [50];
      obj["hiddenPageinfoLink"] = true;
      obj["paginationLoop"] = true;
      obj["paginationPreText"] = "<i class='fa fa-arrow-left'></i>上一页";
      obj["paginationNextText"] = "下一页<i class='fa fa-arrow-right'></i>";
      obj["height"] = ajustHeight;
    }
    $("#table_rw table").bootstrapTable(obj);
    setTimeout(() => {
      $("#table_rw table").bootstrapTable("resetView", ajustHeight);
    }, 100)
  }


  inittable_zdsbClient(data: any): void {
    const that = this;
    $("#table_zdsb table").bootstrapTable('destroy');
    const obj = {
      classes: 'table  table-bordered', //没有 border,默认是 table table-hover
      locale: 'zh-CN',
      sidePagination: "client", //分页方式：client 客户端分页，server 服务端分页（*）
      pageSize: 20, //每页的个数
      pageNumber: 1, //默认是1
      pageList: [20, 30],
      pagination: true, //是否显示分页（*）  默认false
      paginationHAlign: 'right', //right, left
      paginationVAlign: 'bottom', //bottom, top, both
      paginationDetailHAlign: 'left', //right, left
      data: data,
      columns: [{
        title: '终端名称',
        field: 'scdzmc',
        cellStyle: function () {
          return {
            classes: 'td1'
          }
        },
      }, {
        title: '操作',
        field: 'caozuo',
        cellStyle: function () {
          return {
            classes: 'td2'
          }
        },
        events: that.myevents,
        formatter: function (v) {
          let str: string = "";
          str += "<button type='button' class='btn btn-xs btn-info info_zdsb'><i class='fa fa-paper-plane'></i> 查看轨迹</button>";
          return str;
        }
      }]
    };
    const ajustHeight = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 220;
    if (this.sysBase == "61") {
      obj.pageSize = 50;
      obj.pageList = [50];
      obj["hiddenPageinfoLink"] = true;
      obj["paginationLoop"] = true;
      obj["paginationPreText"] = "<i class='fa fa-arrow-left'></i>上一页";
      obj["paginationNextText"] = "下一页<i class='fa fa-arrow-right'></i>";
      obj["height"] = ajustHeight;
    } else {
      obj.pageSize = 50;
      obj.pageList = [50];
      obj["hiddenPageinfoLink"] = true;
      obj["paginationLoop"] = true;
      obj["paginationPreText"] = "<i class='fa fa-arrow-left'></i>上一页";
      obj["paginationNextText"] = "下一页<i class='fa fa-arrow-right'></i>";
      obj["height"] = ajustHeight;
    }
    $("#table_zdsb table").bootstrapTable(obj);
    setTimeout(() => {
      $("#table_zdsb table").bootstrapTable("resetView", ajustHeight);
    }, 100)
  }


  inittable_bqsbClient(data: any): void {
    const that = this;
    $("#table_dzbqsb table").bootstrapTable('destroy');
    const obj = {
      classes: 'table  table-bordered', //没有 border,默认是 table table-hover
      locale: 'zh-CN',
      sidePagination: "client", //分页方式：client 客户端分页，server 服务端分页（*）
      pageSize: 20, //每页的个数
      pageNumber: 1, //默认是1
      pageList: [20, 30],
      pagination: true, //是否显示分页（*）  默认false
      paginationHAlign: 'right', //right, left
      paginationVAlign: 'bottom', //bottom, top, both
      paginationDetailHAlign: 'left', //right, left
      data: data,
      columns: [{
        title: '标签ID',
        field: 'id',
        cellStyle: function () {
          return {
            classes: 'td1'
          }
        },
      }, {
        title: "试卷包名称",
        field: "sjbmc",
        cellStyle: function () {
          return {
            classes: 'td2'
          }
        },
      }, {
        title: '操作',
        cellStyle: function () {
          return {
            classes: 'td2'
          }
        },
        events: that.myevents,
        formatter: function (v) {
          let str: string = "";
          str += "<button type='button' class='btn btn-xs btn-info info_dzbqsb'><i class='fa fa-paper-plane'></i> 查看轨</button>";
          return str;
        }
      }]
    };
    const ajustHeight = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 220;
    if (this.sysBase == "61") {
      obj.pageSize = 50;
      obj.pageList = [50];
      obj["hiddenPageinfoLink"] = true;
      obj["paginationLoop"] = true;
      obj["paginationPreText"] = "<i class='fa fa-arrow-left'></i>上一页";
      obj["paginationNextText"] = "下一页<i class='fa fa-arrow-right'></i>";
      obj["height"] = ajustHeight;
    } else {
      obj.pageSize = 50;
      obj.pageList = [50];
      obj["hiddenPageinfoLink"] = true;
      obj["paginationLoop"] = true;
      obj["paginationPreText"] = "<i class='fa fa-arrow-left'></i>上一页";
      obj["paginationNextText"] = "下一页<i class='fa fa-arrow-right'></i>";
      obj["height"] = ajustHeight;
    }
    $("#table_dzbqsb table").bootstrapTable(obj);
    setTimeout(() => {
      $("#table_dzbqsb table").bootstrapTable('resetView', ajustHeight);
    }, 100)
  }

  @HostListener("window:myevents", ["$event"])
  myevents = {
    "click .info_rw": function (e, value, row, index) {
      this.s_obj_lsgj.cxlx = "sjysrw";
      this.s_obj_lsgj.id = row.ysrwbh;
      // 显示表单，初始化显示的时间是，任务的开始时间和结束时间
      const rwkssj = this.commservice.removeSpace(false, row.rwkssj);
      const rwjssj = this.commservice.removeSpace(false, row.rwjssj);
      $("#s_sbtime").val(rwkssj);
      $("#s_edtime").val(rwjssj)
      this.timerangewarnflag = false;
      this.timerangewarntext = "";

      //轨迹处理方式
      const rwglsblx = row.rwglsblx;
      if (rwglsblx == "sczdsb") {
        this.cllx = 'jp';
      } else if (rwglsblx == "dzbqsb") {
        this.cllx = 'ph';
      }
      $("#dwlx input[type='checkbox']").prop("checked", false);
      this.s_obj_lsgj.dwlxList.length = 0;
      $("#dwlx").hide();
      $("#mymodal").modal({
        keyboard: true,
        backdrop: "static"
      });
    }.bind(this),
    "click .info_zdsb": function (e, value, row, index) {
      this.s_obj_lsgj.cxlx = "sczdsb";
      this.s_obj_lsgj.id = row.id;
      $("#s_sbtime").val("");
      $("#s_edtime").val("");
      this.timerangewarnflag = false;
      this.timerangewarntext = "";
      //轨迹处理方式
      this.cllx = 'jp';
      $("#dwlx input[type='checkbox']").prop("checked", false);
      this.s_obj_lsgj.dwlxList.length = 0;
      $("#dwlx").hide();
      $("#mymodal").modal({
        keyboard: true,
        backdrop: "static"
      });

    }.bind(this),
    "click .info_dzbqsb": function (e, value, row, index) {
      this.s_obj_lsgj.cxlx = "dzbqsb";
      this.s_obj_lsgj.id = row.id;
      $("#s_sbtime").val("");
      $("#s_edtime").val("");
      this.timerangewarnflag = false;
      this.timerangewarntext = "";
      //轨迹处理方式
      this.cllx = 'jp';
      $("#dwlx input[type='checkbox']").prop("checked", false);
      this.s_obj_lsgj.dwlxList.length = 0;
      $("#dwlx").show();
      $("#mymodal").modal({
        keyboard: true,
        backdrop: "static"
      });
    }.bind(this)
  }

  /**
   * 查询历史轨迹数据
   */
  trailIng(): void {
    // 判断时间的合法性
    if (!this.judgeStime()) {
      return
    }
    this.timerangewarnflag = false;
    this.s_obj_lsgj.kssj = $("#s_sbtime").val();
    this.s_obj_lsgj.jssj = $("#s_edtime").val();
    // 判断速度
    $(".mt-radio-inline input").each((index, item) => {
      if (item.checked) {
        this.hfSpeed = item.value;
      }
    });
    // 定位类型
    $("#dwlx input").each((index, item) => {
      const checked = item.checked;
      if (checked) {
        this.s_obj_lsgj.dwlxList.push(item.defaultValue);
      }
    });
    // 清空地图的所有覆盖物
    this.map.clearMap();
    this.carmarker = null;
    this.passedPolyline = null;
    $("#mymodal").modal("hide");
    const url = "sjgz/gjcx/cxlsgj";
    this.itservice.kwPtPost(url, this.s_obj_lsgj).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            let lsgjList = resp.lsgjList;
            if (lsgjList && lsgjList.length) {
              //## 临时 处理,去掉  fxj是 0.0的数据
              // lsgjList = lsgjList.filter((item) => {
              //   return Number(item.fxj) != 0;
              // });
              // const lsgjList_sigle: any[] = [];
              // const helpBuffer: any[] = []; // 经纬度json字符串去重使用
              // lsgjList.forEach((item) => {
              //   const obj = {
              //     jd: item.jd,
              //     wd: item.wd
              //   };
              //   const jsonstr = JSON.stringify(obj);
              //   if (helpBuffer.indexOf(jsonstr) == -1) {
              //     helpBuffer.push(jsonstr);
              //     lsgjList_sigle.push(item);
              //   }
              // });

              //#### end 临时 处理
              //1---任务中，任务关联类型是 sczdsb 的，做纠偏；  dzbqsb 的，做平滑
              //2--终端或者标签的，做纠偏
              // if (this.cllx == 'jp') {
              //   // 做纠偏
              //   // this.handTrail(lsgjList,3);
              // } else if (this.cllx == 'ph') {
              //   // 做平滑
              //   this.handTrail(lsgjList, 2);
              // }
              this.handTrail(lsgjList, 1);
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.trailIng();
        }
      });
    })
  }


  /**
   *
   * @param lssjlist返回的是  火星坐标（高德坐标，已经转换过gps坐标了）
   * @param {number} handerlx
   * 1--原始
   * 2--仅平滑
   * 3--仅纠偏
   */
  handTrail(lssjlist: any, handerlx: number): void {
    const that = this;
    let linearr: any[] = [];
    switch (handerlx) {
      case 1: {
        linearr = lssjlist.map((item) => {
          return [item.jd, item.wd];
        });
        this.drawLine(linearr);
      }
        break;
      case 2: {
        linearr = lssjlist.map((item) => {
          return [item.jd, item.wd];
        });
        linearr = this.handPH(linearr, 10);
        this.drawLine(linearr);
      }
        break;
      case 3: {
        if (lssjlist.length > 1) {
          const graspList = this.converTograspList(lssjlist); // 纠偏数据源
          const list: any[] = [];
          const list_draw: any[] = []; // 纠偏后的
          let convert_num: number = Math.ceil(graspList.length / 499);
          for (let i = 0; i < convert_num; i++) {
            list.push(graspList.slice(i * 499, (i + 1) * 499));
          }
          list.forEach((arr, index) => {
            this.converToTraillist(arr, (list) => {
              list_draw[index] = list;
              convert_num--;
              this.covvertAllok(convert_num, list_draw);
            });
          });
        } else {
          this.handTrail(lssjlist, 1);  // 只有一个点，不能做纠偏
        }
      }
        break;
    }
  }

  /**
   * 判断是否转化完毕,仅纠偏
   */
  covvertAllok(convertnum: number, list_draw: any): void {
    const that = this;
    if (convertnum == 0) {
      let linearr: any[] = [];
      list_draw.forEach((item) => {
        linearr = linearr.concat(item);
      });
      this.drawLine(linearr);
    }
  }


  drawLine(linearr: any): void {
    // 绘制轨迹
    const that = this;
    const dashLine = new AMap.Polyline({
      map: this.map,
      zIndex: 50, //  折线覆盖物的叠加顺序。默认叠加顺序，先添加的线在底层，后添加的线在上层  ,默认50
      path: linearr,
      strokeStyle: "dashed",    // 线条样式，
      strokeColor: "#FF4944",  // 线条颜色
      strokeOpacity: 0.8,
      strokeWeight: 7,  // 线条宽度，单位：像素
      showDir: true, // 是否延路径显示白色方向箭头,默认false。Canvas绘制时有效，建议折线宽度大于6时使用；
    });
    if (!this.passedPolyline) {
      this.passedPolyline = new AMap.Polyline({
        map: this.map,
        zIndex: 60, //  折线覆盖物的叠加顺序。默认叠加顺序，先添加的线在底层，后添加的线在上层  ,默认50
        strokeStyle: "solid",    // 线条样式，
        strokeColor: "blue",  // 线条颜色
        strokeOpacity: 0.8,
        strokeWeight: 7,  // 线条宽度，单位：像素
        showDir: true, // 是否延路径显示白色方向箭头,默认false。Canvas绘制时有效，建议折线宽度大于6时使用；
      });
    }
    if (!this.carmarker) {
      this.carmarker = new AMap.Marker({
        map: this.map,
        position: linearr[0],
        offset: new AMap.Pixel(-17, -9),
        autoRotation: true,  // 是否自动旋转。点标记在使用moveAlong动画时，路径方向若有变化，点标记是否自动调整角度，默认为false。广泛用于自动调节车辆行驶方向。
        angle: -90,
        icon: new AMap.Icon({
          // 34x18px
          image: "assets/img/sjgz/car_blue.png",
          imageOffset: new AMap.Pixel(0, 0)
        }),
      });
    }
    // 回放控制
    this.carmarker.moveAlong(linearr, this.hfSpeed, function (k) {
      return k;
    }, false);
    this.carmarker.on("moving", function (e) {
      const hasrunpath = e.passedPath;
      that.passedPolyline.setPath(hasrunpath);
      // 如果回放速度特别快（that.hfwcExistSpeed km/h）,那么会出现绘制误差
      if (that.hfSpeed > that.hfwcExistSpeed) {
        // 线纠正
        that.passedPolyline.setPath(linearr);
        // 车marker位置纠正
        const lastpostion = linearr[linearr.length - 1];
        that.carmarker.setPosition(lastpostion);
      }
    });

    // 回放结束
    this.carmarker.on("movealong", function () {

    });
  }

  /**
   * 转换为 grasp 要求的数据格式，后续用来纠正
   * @param lssjlist
   * @returns {any}
   */
  converTograspList(lssjlist: any): any {
    const grasplist: any[] = [];
    lssjlist.forEach((obj, index) => {
      const info: any = {
        x: 0.0,
        y: 0.0,
        sp: 0,
        ag: 0,
        tm: 0
      };
      const jdv = obj.jd;
      const wdv = obj.wd;
      const speedv = obj.sd ? Number(obj.sd) : 0;
      const fxjv = Number(obj.fxj) ? Number(obj.fxj) : 0;
      info.x = parseFloat(jdv);
      info.y = parseFloat(wdv);
      info.sp = parseFloat(speedv.toString());
      info.ag = parseFloat(fxjv.toString()); // ag [0 360]  与正北方向的顺时针夹角

      if (index == 0) {
        const nowms = this.commservice.convertTimeToInt(obj.sj);
        const nowseconds = Math.round(nowms / 1000);
        info.tm = nowseconds;
      } else {
        const nowms = this.commservice.convertTimeToInt(obj.sj);
        const nowseconds = Math.round(nowms / 1000);
        const cjtime = nowseconds - grasplist[0].tm;
        info.tm = cjtime;
      }
      grasplist.push(info);
    });
    this.commservice.warn("converTograspList", "纠偏数据源", grasplist);
    return grasplist;
  }

  /**
   * 道路纠偏
   * @param grasplist
   * @returns {any}
   * 返回  路径 [ [jd,wd],[jd,wd]]
   * arr.length 不能超过 500
   */
  converToTraillist(grasplist: any, callback: Function): void {
    this.graspobj.driving(grasplist, (error, result) => {
      if (!error) {
        const path2 = [];
        const newPath = result.data.points;
        newPath.forEach((item) => {
          path2.push([item.x, item.y]);
        });
        callback(path2);
      } else {
        this.commservice.myswal("warning", "道路纠正错误", "", "ts", null);
      }
    });
  }


  judgeStime(): boolean {
    let sret = true;
    const stimev = $("#s_sbtime").val();
    const etimev = $("#s_edtime").val();
    const stimeInit = this.commservice.convertTimeToInt(stimev);
    const etimeInit = this.commservice.convertTimeToInt(etimev);
    if (stimeInit >= etimeInit) {
      this.timerangewarnflag = true;
      this.timerangewarntext = "开始时间不能大于或者等于结束时间";
      sret = false;
    } else {
      // if (etimeInit - stimeInit > 8 * 60 * 60 * 1000) {
      //   this.timerangewarnflag = true;
      //   this.timerangewarntext = "查询时间段超过8小时，请控制在8小时内";
      //   sret = false;
      // }
    }
    return sret;
  }

  /**
   * 对经纬度坐标做2点平滑处理
   * @param arr
   * @param {number} phd  平滑度
   * @returns {any}
   */
  handPH(arr: any, phd: number): any {
    const pharr: any = [];
    arr.forEach((item, index) => {
      const jdlist: any[] = [];
      const wdlist: any[] = [];
      for (let i = index; i < (Number(phd) + Number(index)); i++) {
        if (i < arr.length) {
          jdlist.push(arr[i][0]);
          wdlist.push(arr[i][1]);
        }
      }
      const phjd = this.commservice.sum(jdlist) / jdlist.length;
      const phwd = this.commservice.sum(wdlist) / wdlist.length;
      pharr.push([phjd, phwd])
    });
    // console.log("平滑后的数据", phd, pharr);
    return pharr;
  }


  /**
   * 处理页面的相关元素尺寸
   */
  initSize(): void {
    const h = this.commservice.getViewPort().height - this.commservice.topmenuH - this.commservice.topH;
    this.pagesize.pageh = `${h}px`;
    this.pagesize.rpanelwinit = this.commservice.getViewPort().width - this.pagesize.lpanelwinit - 20; //
    this.pagesize.rpanelwstr = `${this.pagesize.rpanelwinit}px`;
  }

  initMap(): void {
    const that = this;
    this.map = new AMap.Map("mapdiv", {
      resizeEnable: true, //是否监控地图容器尺寸变化，默认值为false
      zoom: 11, //地图显示的缩放级别，若center与level未赋值，地图初始化默认显示用户所在城市范围，没有center（中心点）和level ，所以这个暂时无效
    }).on('click', function (e) {
      console.log(e.lnglat);
    });
    AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', "AMap.GraspRoad"],
      function () {
        //缩放，平易等工具条
        that.map.addControl(new AMap.ToolBar());
        //比例尺
        that.map.addControl(new AMap.Scale());
        //鹰眼
        that.map.addControl(new AMap.OverView({
          isOpen: false
        }));
        // 轨迹纠偏
        that.graspobj = new AMap.GraspRoad();
      });
  }

  /**
   * 查询范围树的 显示与否控制
   */
  searchTreectr(): void {
    this.treeshow = !this.treeshow;
  }

  /**
   * 1---左侧控制
   * msg--右下角的消息控制
   */
  lpanelCtr(flag: string): void {
    if (flag == "l") {
      const lshow = this.pagesize.lpanelshow;
      if (lshow) {
        this.pagesize.lpanelshow = false;
        $(".lpanel").animate({
          width: 20
        }, 500);
        this.pagesize.rpanelwinit = this.pagesize.rpanelwinit + (this.pagesize.lpanelwinit - 20);
        this.pagesize.rpanelwstr = `${this.pagesize.rpanelwinit}px`;
        $(".rpanel").animate({
          marginLeft: "20px"
        }, 500);
        $("#lformRoom").hide();
      } else {
        this.pagesize.lpanelshow = true;
        $(".lpanel").animate({
          width: 475
        }, 500);
        this.pagesize.rpanelwinit = this.pagesize.rpanelwinit - (this.pagesize.lpanelwinit - 20);
        this.pagesize.rpanelwstr = `${this.pagesize.rpanelwinit}px`;
        $(".rpanel").animate({
          marginLeft: this.pagesize.lpanelwinit + "px"
        }, 500);
        $("#lformRoom").show();
      }
    }
  }

  /**
   * 查询表单
   */
  createsearchForm(): void {
    const cxlxData = [{
      code: "sjysrw",
      name: "运送任务"
    }, {
      code: "sczdsb",
      name: "手持终端"
    }, {
      code: "dzbqsb",
      name: "电子标签"
    }];
    $("#cxlxSelect").empty();
    let str: string = "";
    cxlxData.forEach((item) => {
      str += "<option value='" + item.code + "'>" + item.name + "</option>";
    });
    $("#cxlxSelect").append(str);
    $("#cxlxSelect").selectpicker({
      size: 5
    });
    this.s_obj.cxlx = cxlxData[0].code;
  }

  initstime(): void {
    const that = this;
    // 轨迹回放的世间选择
    $('.datetimepickerB_content').datetimepicker({
      autoclose: true,
      language: 'zh-CN',
      format: 'yyyy-mm-dd hh:ii:ss',
      pickerPosition: "bottom-left",
      minView: 0
    }).on("changeDate", function (ev) {
      const selectdate = ev.date.valueOf(); // 实际时间+ 8h
      // 结束时间不能小于开始时间,
      $(".datetimepickerE_content").datetimepicker("setStartDate", new Date(selectdate - 8 * 60 * 60 * 1000));
    });
    $('.datetimepickerE_content').datetimepicker({
      autoclose: true,
      language: 'zh-CN',
      format: 'yyyy-mm-dd hh:ii:ss',
      pickerPosition: "bottom-left",
      minView: 0
    }).on("changeDate", function (ev) {
      const selectdate = ev.date.valueOf(); // 实际时间+ 8h
      // 开始时间不能大于结束时间
      $(".datetimepickerB_content").datetimepicker("setEndDate", new Date(selectdate - 8 * 60 * 60 * 1000));
    });
  }

  /**
   * 获取用户信息
   */
  getuserinfo(): void {
    this.commservice.getUserinfo((info) => {
      this.userinfo = info;
      const userrole = this.commservice.getuserDepartmentFl(info.cslx, info.csid, info.nowrolecode);
      if (userrole === "Z3") {
        this.s_obj.ksgljgid = info.csid;
        this.s_obj.ksgljgidmc = info.csmc;
        this.search_n();
      } else if (userrole === "Z1" || userrole === "Z2") {
        this.initsearchTree();
      }
    });
  }

  constructor(private localStorageService: LocalStorageService,
              private commservice: CommService,
              private itservice: MyhttpService) {

  }

  ngOnInit() {
    this.s_obj.ksjhbh = this.localStorageService.get("hksjh");
    this.commservice.getSysmsg2((resp) => {
      this.sysBase = resp.sysBase;
    });
    this.initSize();
    this.initMap();
    this.createsearchForm();
    this.getuserinfo();
    this.initstime();
  }

  ngOnDestroy() {

  }

}
